using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerDamager : MonoBehaviour
{
    private PlayerMovement playerMovement;

    [Header("Health Settings")]
    [SerializeField] private int maxHealth;
    [SerializeField] private int currentHealth;

    [Header("Hit Settings")]
    [SerializeField] private float slowSpeed;
    [SerializeField] private float slowDuration;
    [SerializeField] private float invincibilityTime;
    
    private float lastHitTime;
    private float originalSpeed;
    private bool isSlowed;
    private bool isDead;

    private void Awake()
    {

        playerMovement = GetComponent<PlayerMovement>();
    }
    private void Start()
    {
        currentHealth = maxHealth;
    }
    public void TakeDamage(int dmg)
    {
        if ( isDead || Time.time - lastHitTime < invincibilityTime)
            return;

        lastHitTime = Time.time;
        currentHealth -= dmg;

        if (currentHealth <= 0)
        {

            Die();
            return;
        }

        if (!isSlowed)
            StartCoroutine(Hit());
    }
    private void Die()
    {
        if (isDead)
            return;
        isDead = true;
        if (playerMovement != null)
        {
            playerMovement.enabled = false;
        }
        if (GameOverManager.Instance != null)
        {
            GameOverManager.Instance.ShowGameOver();
        }
    }
    #region Hit
    private IEnumerator Hit()
    {
        isSlowed = true;

        originalSpeed = playerMovement.GetSpeed();
        playerMovement.SetSpeed(slowSpeed);

        yield return new WaitForSeconds(slowDuration);

        playerMovement.SetSpeed(originalSpeed);
        isSlowed = false;
    }
    #endregion

    #region Requests
    public int MaxHealth()
    { 
        return maxHealth;
    }
    public int CurrentHealth()
    {
        return currentHealth;
    }
    public bool IsDead()
    {
        return isDead;
    }
    #endregion
}
